<template>
  <div class="analyse-main">
    <div class="charts-body">
      <el-row style="height: 100%" :gutter="12">
        <el-col :span="4" class="form-main">
          <div class="file-name">
            <el-tooltip :content="fileName">
              <span class="file-wrapper">{{ fileName }}</span>
            </el-tooltip>
            <el-button style="margin-left: 10px;" @click="refreshPage">重新加载</el-button>
          </div>
          <radar-left @filter="filterSign" />
        </el-col>
        <el-col :span="16" class="chart-item">
          <div class="chart-container" style="flex: 1">
            <data-chart
              v-if="config.chart"
              id="signalAnalyse"
              title="频谱图"
              :data="chartData"
              :config="config"
            />
          </div>
          <div class="picker-list">
            <el-tabs
              v-model="activeName"
              type="border-card"
              class="tabs"
            >
              <el-tab-pane label="雷达信号" name="first">
                <el-descriptions border>
                  <!-- <el-descriptions-item label="批号">{{ info.startTime }}</el-descriptions-item> -->
                  <!-- <el-descriptions-item label="批号">18000</el-descriptions-item> -->
                  <el-descriptions-item label="载频MHz">{{ signResults.CF }}</el-descriptions-item>
                  <el-descriptions-item label="重周us">{{ signResults.PRI }}</el-descriptions-item>
                  <el-descriptions-item label="幅度">{{ signResults.AMP }}</el-descriptions-item>
                  <!-- <el-descriptions-item label="EDW类型">18000</el-descriptions-item> -->
                  <el-descriptions-item label="载频个数">{{ signResults.CF_num }}</el-descriptions-item>
                  <el-descriptions-item label="重周个数">{{ signResults.PRI_num }}</el-descriptions-item>
                  <el-descriptions-item label="幅度最大值">{{ signResults.AMP_max }}</el-descriptions-item>
                  <!-- <el-descriptions-item label="脉内调制类型">18000</el-descriptions-item> -->
                  <el-descriptions-item label="载频类型">{{ signResults.CF_type }}</el-descriptions-item>
                  <el-descriptions-item label="重周类型">{{ signResults.PRI_type }}</el-descriptions-item>
                  <el-descriptions-item label="幅度最小值">{{ signResults.AMP_min }}</el-descriptions-item>
                  <!-- <el-descriptions-item label="载频MHz">18000</el-descriptions-item> -->
                  <el-descriptions-item label="脉宽us">{{ signResults.PW }}</el-descriptions-item>
                  <el-descriptions-item label="重周容差">{{ signResults.PRI_tol }}</el-descriptions-item>
                  <el-descriptions-item label="载频容差">{{ signResults.CF_tol }}</el-descriptions-item>
                  <!-- <el-descriptions-item label="脉内调制类型">18000</el-descriptions-item> -->
                  <!-- <el-descriptions-item label="脉宽类型">18000</el-descriptions-item>
                  <el-descriptions-item />
                  <el-descriptions-item /> -->
                  <el-descriptions-item label="方位角">{{ signResults.aoa }}</el-descriptions-item>
                  <el-descriptions-item label="脉宽容差">{{ signResults.PW_tol }}</el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
              <el-tab-pane label="峰值表" name="second">
                <el-table border :data="maxList" height="300">
                  <el-table-column label="峰值" prop="num" width="60" />
                  <el-table-column label="频率" prop="rate" />
                  <el-table-column label="幅度" prop="am" />
                  <el-table-column label="频率差值" prop="ratediff" />
                  <el-table-column label="幅度差值" prop="amdiff" />
                </el-table>
              </el-tab-pane>
              <!-- <el-tab-pane label="参数估计">
                <el-table
                  border
                  :data="paramsRsp"
                  height="300"
                >
                  <el-table-column label="参数名" prop="label" width="200" />
                  <el-table-column label="参数值" prop="value" width="400" />
                </el-table>
              </el-tab-pane> -->
            </el-tabs>
          </div>
        </el-col>
        <el-col class="form-main" :span="4">
          <radar-right @update:chartData="updateChartData" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup name="RadarAnalyse">
  import DataChart from '@/components/DataChart'
  import useChartsStore from '@/store/modules/charts'
  import useRadarScanForm from '@/store/modules/form/radarScanForm'
  import useChartOptions from '@/common/hooks/chartOptions'
  import { queryRadarFft } from '@/api/charts'
  import { numToPlot, plotToNum } from '@/utils/utils'
  import { cloneDeep, round } from 'lodash'
  
  let oldFileName = null
  const radarLeft = defineAsyncComponent(() => import('@/views/analyse/panels/scan/RadarLeft.vue'))
  const radarRight = defineAsyncComponent(() => import('@/views/analyse/panels/scan/RadarRight.vue'))
  const chartsStore = useChartsStore()
  const radarScanForm = useRadarScanForm()
  const chartData = ref([])
  const config = ref({})
  const loaded = ref(false)
  const activeName = ref('first')
  const signResults = ref([])
  const pickTable = ref(null)
  const fileName = computed(() => chartsStore.radarfile.fileName)
  const { global } = chartsStore
  // 点击信号分选同步表单
  const form = reactive({
    centerfreIn: 0,
    samplingRate: 0,
    ifBw: 0,
    bitRate: 0,
    iqReserve: 0,
    logarithm: 0,
  })
  const refreshPage = () => {
    window.location.reload();
  }
  const maxList = computed(() => {
    const temp = cloneDeep(chartData.value)
    if (!temp || temp.length === 0) {
      return []
    }
    temp.sort((a, b) => a - b)
    const maxAm = temp.pop()
    const maxAmMapPlot = transToPlot(chartData.value.indexOf(maxAm))
    const result = [{
      num: 1,
      am: maxAm + 'dB',
      rate: numToPlot(maxAmMapPlot),
      ratediff: numToPlot(0),
      amdiff: '0dB'
    }]
    while (result.length < 8 && temp.length > 0) {
      const last = result[result.length - 1]
      const lastAm = parseInt(last.am)
      const item = temp.pop()
      if (item === lastAm) {
        continue
      }
      const rate = transToPlot(chartData.value.indexOf(item))
      if (Math.abs(rate - plotToNum(last.rate)) > 100) {
        result.push({
          num: result.length + 1,
          am: item + 'dB',
          rate:  numToPlot(rate),
          amdiff: (maxAm - item) + 'dB',
          ratediff: numToPlot(maxAmMapPlot - rate)
        })
      } 
    }
    return result
  })
  // 从下标转化为对应频率
  const transToPlot = (num) => {
    const { global } = chartsStore
    const left = global.radarcenterFreqIn - global.radarintermediateFrequency
    return (num / chartData.value.length) * global.radarintermediateFrequency + left
  }
  // const paramsRsp = ref([
  //   { label: '载频', value: '', key: 'cf_Out' },
  //   { label: '调制类型', value: '', key: 'type_Out' },
  //   { label: '功率', value: '', key: 'power_Out' },
  //   { label: '3DB带宽', value: '', key: 'xbw_Out' },
  //   { label: 'Beta带宽（99%功率）', value: '', key: 'betaBW_Out' },
  // ])
  const formSync = () => {
    form.centerfreIn = radarScanForm.fileCenterFreIn
    form.ifBw = radarScanForm.fileIfBw
    form.bitRate = radarScanForm.fileBitRate
    form.samplingRate = radarScanForm.fileSamplingRate
    form.iqReserve = radarScanForm.iqReserve
    form.logarithm = radarScanForm.logarithm
  }
  const updateChartData = (data) => {
    chartData.value = data
    radarScanForm.endPoint = chartData.value.length - 1
    radarScanForm.allLen = chartData.value.length
    chartsStore.settings.IQNum = chartData.value.length
  }
  const filterSign = async () => {
    radarScanForm.setCenterFre()
    const body = generateBody()
    await queryvalueList(body)
    radarScanForm.setFileParams(body)
    radarScanForm.init(body.intermediateFrequency, body.centerfreIn)
  }
  const generateBody = () => {
    const { fileName, uploadTime } = chartsStore.getRadarInfo()
    const { fileCenterFreIn, fileSamplingRate, fileIfbw, fileBitRate, iqReverse, logarithm, downCenterFreIn,path } = radarScanForm
    return { 
      fileName, 
      centerfreIn: fileCenterFreIn,
      samplingRate: fileSamplingRate,
      intermediateFrequency: fileIfbw,
      bitRate: fileBitRate,
      iqReverse: Number(iqReverse),
      logarithm: Number(logarithm),
      path:path,
      uploadTime,
    }
  }
  // const pick = (item) => {
  //   radarScanForm.init(item.bw, item.cf)
  // }
  const queryvalueList = async (body) => {
    oldFileName = body.fileName
    body.startPoint = undefined
    body.endPoint = undefined
    const ddcFlag  = chartsStore.getRadarDownConversion().ddcFlag
    const filterFlag  = chartsStore.getRadarFilting().filterFlag
    if(ddcFlag){
      const doubleMapKey = chartsStore.getRadarDownConversion().doubleMapKey
      body.doubleMapKey = doubleMapKey
      body.ddcFlag = ddcFlag
    }
    if(filterFlag){
      const doubleMapKey = chartsStore.getRadarFilting().doubleMapKey
      body.doubleMapKey = doubleMapKey
      body.filterFlag = filterFlag
    }
    const { data } = await queryRadarFft(body)
    updateChartData(data.valueList)
    radarScanForm.endPoint = chartData.value.length - 1
    radarScanForm.allLen = chartData.value.length
    radarScanForm.iqNum = data.pIQ_In
    radarScanForm.capital = false
    body.ddcFlag = false
    body.filterFlag = false
    signResults.value = data.narrowBandSortNew.data.radar_result
    console.log('body', body)
    chartsStore.setGlobal('radarcenterFreqIn', body.centerfreqIn | 0)
    chartsStore.setGlobal('radarintermediateFrequency', body.intermediateFrequency | 0)
    formSync()
    // setSignalEntity(data.signalITUEntity)
  }
  const setSignalEntity = (val) => {
    const rates = ['cf_Out', 'xbw_Out', 'betaBW_Out']
    const dbm = 'power_Out'
    const type = 'type_Out'
    paramsRsp.value.forEach(item => {
      const p = val[item.key]
      if (rates.includes(item.key)) {
        item.value = numToPlot(p)
      } else if (item.key === dbm) {
        item.value = round(p, 2) + 'dbm'
      } else {
        item.value = p
      }
    })
  }
  const genearteConfig = () => {
    const { chartOptions } = useChartOptions('spectrum')
    config.value = {
      type: 'static',
      chart: computed(() => {
        const options = cloneDeep(chartOptions.value)
        options.chart.height = document.body.clientHeight - 416 > 500 ? document.body.clientHeight - 516 : 500
        const left = radarScanForm.pickCf - radarScanForm.pickBw / 2
        const axis = options.xAxis
        axis.max = radarScanForm.len - 1
        axis.tickInterval = (radarScanForm.len - 1) / 10
        axis.labels.formatter = function () {
          const val = (this.value / (radarScanForm.len - 1)) * radarScanForm.pickBw + left
          return numToPlot(val)
        }
        const yAxis = options.yAxis
        yAxis.max = radarScanForm.refLevel
        yAxis.min = radarScanForm.refLevel - radarScanForm.amScale * 10
        yAxis.tickInterval = radarScanForm.amScale
        yAxis.tickAmount = 11
        if (form.logarithm || radarScanForm.capital) {
          options.yAxis.max = undefined
          options.yAxis.min = undefined
          yAxis.tickInterval = undefined
        }
        return options
      }),
      viewNum: 'all',
      start: computed(() => radarScanForm.startPoint),
      hideBar: true,
    }
  }
  const init = async () => {
    const body = cloneDeep(chartsStore.getRadarInfo())
    body.ddcFlag = false
    body.filterFlag = false
    body.samplingRate = body.samplerateIn
    if (loaded.value || oldFileName === body.fileName) {
      return
    }
    loaded.value = true
    await queryvalueList(body)
    radarScanForm.setFileParams(body)
    radarScanForm.init(global.radarintermediateFrequency, global.radarcenterFreqIn)
    genearteConfig()
  }
  watchEffect(() => {
    const { radarfile } = chartsStore
    radarScanForm.fileCenterFreIn = radarfile.centerfreqIn // 中心频率
    radarScanForm.fileSamplingRate = radarfile.samplerateIn // 采样率
    radarScanForm.fileIfbw = radarfile.intermediateFrequency // 中频带宽
    // radarScanForm.fileBitRate = radarfile.bitRate
    radarScanForm.iqReverse = !!radarfile.iqReverse
    radarScanForm.logarithm = !!radarfile.logarithm
    const params = chartsStore.getParamsEstimate()
    // setSignalEntity(params)
  })
  onMounted(async () => {
    await init()
  })
  onBeforeMount(() => {
    // 将本地缓存写入store里面的内容
    chartsStore.readStorage()
  })
  onUnmounted(() => {
    // 将store里面的内容写入本地缓存
    chartsStore.writeStorage()
  })
  onActivated(async () => {
    console.log('onActivated')
    await init()
  })
  onDeactivated(() => { loaded.value = false })
  window.onunload = function() {
    chartsStore.writeStorage()
  }
</script>

<style scoped lang="scss">
  .analyse-main {
    height: 100%;
    display: flex;
    flex-direction: column;
    .charts-body {
      flex: 1;
      .show-table {
        height: 100%;
        border-right: 1px solid grey;
      }
      .form-main {
        box-shadow: 0px 0px 1rem 0px rgba(82, 137, 136, 0.08);
        padding: 12px;
        .file-name {
          display: flex;
          align-items: center;
          font-size: 20px;
          font-weight: bold;
          overflow: hidden;
          text-overflow: ellipsis;
          padding-bottom: 16px;
          white-space: nowrap;
          
        }
      }
    }
  }
  .file-wrapper{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
  }
</style>
